import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { GetUserInfo } from "@/api/auth"
import Oidc from "oidc-client"
import { oidcSettings } from "@/api/oidc"

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
    sessionStorage.clear()
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    sessionStorage.setItem('token',token)
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const mgr = new Oidc.UserManager(oidcSettings)
const actions = {
  login({ commit }) {
    return new Promise((resolve, reject) => {
      mgr.getUser().then((data) => {
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        let token = data.access_token
        if(token){
          commit('SET_TOKEN', token)
          setToken(token)
        }
        resolve()
      })
    })
  },
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      GetUserInfo().then((data)=>{
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        let userInfo = {
          name: data.data.name,
          avatar: data.data.avatar
        }
        commit('SET_NAME', userInfo.name)
        commit('SET_AVATAR', userInfo.avatar)
        resolve(userInfo)
      }).catch(error => {
        reject(error)
      })
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

